package com.android.enjoymax;

import android.app.Activity;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class Pictures extends Activity {
	StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
	
	
    /** Called when the activity is first created. */
	public static ArrayList<String> images;
	
    @Override    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pictures);
        
        StrictMode.setThreadPolicy(policy);
 Drawable drawable = this.getResources().getDrawable(R.drawable.background1);
        
	    //Change background of Activity       
	    getWindow().setBackgroundDrawable(drawable);
	    
        getTheImages();
        	
       // getTheImages();
        GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(new ImageAdapter(this));
    }
    public void callSecondScreen(View view)
    {
    		Intent i = new Intent(this, SecondScreen.class);	        
	        startActivity(i);
    }
       
    
    public class ImageAdapter extends BaseAdapter
    {
	    private Context mContext;
	    public ImageAdapter(Context c)
	    {
	    	mContext = c;
	    }
	    public int getCount()
	    {
	    	//return mThumbIds.length;
	    	return images.size();
	    }
	
	    
	    public Object getItem(int position)
	    {
	    	return null;
	    }
	
	    
	    public long getItemId(int position)
	    {
	    	return 0;
	    }
	
	    // create a new ImageView for each item referenced by the Adapter
	    public View getView(int position, View convertView, ViewGroup parent)
	    {
	    final ImageView imageView;
	    if (convertView == null)
	    {
		    imageView = new ImageView(mContext);
		    imageView.setLayoutParams(new GridView.LayoutParams(280, 280));
		    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
		    imageView.setPadding(8, 8, 8, 8);
	    }
	    else
	    {
	    imageView = (ImageView) convertView;
	    }
	    
	    //imageView.setImageResource(R.drawable.icon);
	    imageView.setImageBitmap(getBitmapFromURL(images.get(position)));
	    imageView.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	//here, call the new intent and pass the current image to it for displaying
            	System.out.println("inside the listener");
            	imageView.buildDrawingCache();
            	Bitmap bmap = imageView.getDrawingCache();
            	Intent intent = new Intent(Pictures.this, SecondScreen.class);
            	intent.putExtra("BitmapImage", bmap);
            	System.out.println("new intent called");
            	startActivity(intent);
            }
        });
	    return imageView;
	    
	    }
	    
	    //private Integer[] mThumbIds = {R.drawable.icon, R.drawable.icon,R.drawable.icon, R.drawable.icon,R.drawable.icon, R.drawable.icon,R.drawable.icon, R.drawable.icon,R.drawable.icon, R.drawable.icon};
	    
	    public Bitmap getBitmapFromURL(String src)
	    {
	    	try 
	    	{
	    	URL url = new URL(src);
	    	HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	    	connection.setDoInput(true);
	    	connection.connect();
	    	InputStream input = connection.getInputStream();
	    	Bitmap myBitmap = BitmapFactory.decodeStream(input);
	    	return myBitmap;
	    	} 
	    	catch (IOException e) 
	    	{
	    	e.printStackTrace();
	    	}
	    	return null;
	    }
    }   
    
    
    public void Panaromio_Get_Images(View view)
    {    
    	getTheImages();
    }
    public void getTheImages()
    {
    	String set="public";//for popular photos
    	//strings from and to define the indices of photos to be retrieved. 
    	String from="0";
    	String to="10";
    	//the next 4 params define the min and max locations of the area for which photos are to be obtained
    	String minx="-180";
    	String miny="-90";
    	String maxx="180";
    	String maxy="90";
    	String size="medium";//available values: original, medium, small, thumbnail, square, mini_square
    	String mapfilter="true";//to make photos look better when placed on maps
    	ArrayList<String> images=new ArrayList<String>();
    	
    	images=new DownloadImageTask().getImages(set, from, to, minx, miny, maxx, maxy, size, mapfilter);
    	System.out.println(images); 	
        
    	
    	//show The Image
    	//new DownloadImageTask((ImageView) findViewById(R.id.imageView1)).execute(images.get(0));
   	}

    	//Now the arraylist images holds the URLs of all the images that we need.
    
	
//	protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException 
//	{
//		InputStream in = entity.getContent();
//		StringBuffer out = new StringBuffer();
//		int n = 1;
//		while (n>0) {
//		byte[] b = new byte[4096];
//		n =  in.read(b);
//		if (n>0) out.append(new String(b, 0, n));
//		}
//		return out.toString();
//	}
	
//	protected ArrayList<String> getImages(String set,String from,String to,String minx,String miny,String maxx,String maxy,String size,String mapfilter)
//	{
//		images=new ArrayList<String>();
//		HttpClient httpClient = new DefaultHttpClient();
//		HttpContext localContext = new BasicHttpContext();
//		HttpGet httpGet = new HttpGet("http://www.panoramio.com/map/get_panoramas.php?set="+set+"&from="+from+"&to="+to+"&minx="+minx+"&miny="+miny+"&maxx="+maxx+"&maxy="+maxy+"&size="+size+"&mapfilter="+mapfilter+"");
//		String text = null;
//		try 
//		{
//			HttpResponse response = httpClient.execute(httpGet, localContext);			
//			HttpEntity entity = response.getEntity();
//			text = getASCIIContentFromEntity(entity);
//			JSONObject json = new JSONObject(text);
//			JSONArray jArray=new JSONArray(json.getString("photos"));
//			for(int i=0;i<jArray.length();i++)
//			{	
//				images.add(jArray.getJSONObject(i).getString("photo_file_url"));
//			}
//			
//		} 
//		catch (Exception e) 
//		{
//			e.printStackTrace();
//		}
//		return images;
//	}




}//class ends here

class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
 ImageView bmImage;
 protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException 
	{
		InputStream in = entity.getContent();
		StringBuffer out = new StringBuffer();
		int n = 1;
		while (n>0) {
		byte[] b = new byte[4096];
		n =  in.read(b);
		if (n>0) out.append(new String(b, 0, n));
		}
		return out.toString();
	}
 protected ArrayList<String> getImages(String set,String from,String to,String minx,String miny,String maxx,String maxy,String size,String mapfilter)
	{
		Pictures.images=new ArrayList<String>();
		HttpClient httpClient = new DefaultHttpClient();
		HttpContext localContext = new BasicHttpContext();
		HttpGet httpGet = new HttpGet("http://www.panoramio.com/map/get_panoramas.php?set="+set+"&from="+from+"&to="+to+"&minx="+minx+"&miny="+miny+"&maxx="+maxx+"&maxy="+maxy+"&size="+size+"&mapfilter="+mapfilter+"");
		String text = null;
		try 
		{
			HttpResponse response = httpClient.execute(httpGet, localContext);			
			HttpEntity entity = response.getEntity();
			text = getASCIIContentFromEntity(entity);
			JSONObject json = new JSONObject(text);
			JSONArray jArray=new JSONArray(json.getString("photos"));
			for(int i=0;i<jArray.length();i++)
			{	
				Pictures.images.add(jArray.getJSONObject(i).getString("photo_file_url"));
			}
			
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		return Pictures.images;
	}

 public DownloadImageTask(ImageView bmImage) {
     this.bmImage = bmImage;
 }

 public DownloadImageTask() {
	 
 }
 
 protected Bitmap doInBackground(String... urls) {
     String urldisplay = urls[0];
     Bitmap mIcon11 = null;
     try {
         InputStream in = new java.net.URL(urldisplay).openStream();
         mIcon11 = BitmapFactory.decodeStream(in);
     } catch (Exception e) {
         Log.e("Error", e.getMessage());
         e.printStackTrace();
     }
     return mIcon11;
 }

 protected void onPostExecute(Bitmap result) {
     bmImage.setImageBitmap(result);
 }
}